<template>
  <div class="produce-file">
    <el-container>
      <el-aside style="width: 240px; height: 100vh; background-color: #fff; padding: 10px 20px;border-radius: 8px">
        <el-input v-model="fileData.name" placeholder="请输入地震事件" :suffix-icon="Search" @change="selectByName()" />
        <el-tree style="max-width: 200px;margin-top: 10px;" v-loading="loading" :data="publicList" :props="defaultProps"
          default-expand-all @node-click="handleNodeClick1">
          <template #default="{ data }">
            <img v-if="!data.children" :src="treeIcon.folder" />
            <img v-else :src="treeIcon.file" />
            <span>{{ data.name}}</span>
          </template>
        </el-tree>
      </el-aside>
      <el-main style="width: 100%; background-color: #fff; margin-left: 14px;border-radius: 8px">
        <el-container style="display: flex; justify-content: space-between;">
          <div style="display: flex;font-size: 16px; ">
            <el-button type="primary" size="large" @click="addfile">上传</el-button>
            <el-button type="primary" size="large" @click="downloadList">批量下载</el-button>
            <el-button type="primary" @click="remove" size="large" v-show="isShow">批量删除</el-button>
            <el-button type="primary" size="large" @click="handlePrint" v-show="isShow">打印</el-button>
          </div>
          <div style="margin-right: 100px; display: flex; align-items: center;">
            <div style="font-size: 16px;color: #333;">产出单位：</div>
            <el-select v-model="produceName" placeholder="请选择" size="large" style="width: 200px"
              @change="handleSelectChange">
              <el-option v-for="item in produceList" :key="item.divisionCode" :label="item.divisionName"
                :value="item.divisionCode" />
            </el-select>
          </div>
        </el-container>
        <div style="margin-top: 30px">
          <el-table :data="tableData" style="width: 100%" show-header @selection-change="handleSelectionChange" stripe
            header-cell-class-name="custom-header">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="name" label="名称">
              <template #default="scope">
                <div style="display: flex; align-items: center">
                  <img class="zip" :src="scope.row.imgType" alt="" />
                  <span style="color: #3560F6; margin-left: 10px;font-size: 14px;" @click="Preview(scope.row)">{{
                    scope.row.name
                    }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="earthQuakeName" label="关联地震">
              <template #default="scope">
                <span style="color: #3560F6;font-size: 14px;" @click="jumpViewpage(scope.row)">{{
                  scope.row.earthQuakeName
                  }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="createdUser" label="产出单位" width="100" style="font-size: 14px; color: #333;" />
            <el-table-column prop="fileTypeName" label="文件类型" width="100" style="font-size: 14px; color: #333;" />
            <el-table-column prop="fileSize" label="文件大小" width="100" style="font-size: 14px; color: #333;" />
            <el-table-column prop="createdAt" label="时间" width="200" style="font-size: 14px; color: #333;" />
          </el-table>
        </div>
        <div style="margin-top: 30px">
          <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40]"
            :size="size" :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
            :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { Search } from '@element-plus/icons-vue'
import router from '@/router'
import moment from 'moment'
import download from '@/utils/download'
import * as datarApi from '@/api/file'
// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const size = ref('default')
const disabled = ref(false)
const background = ref(false)
const total = ref(100)
const isShow = ref(true)

const defaultProps = {
  children: 'children',
  label: 'name'
}
// 下拉选项
const produceName = ref('')
const produceList = ref([])
// 删除项,批量下载
let idList = []
let filename = []
const fileData = reactive({
  earthquakeId: '', // 或者设置为 null 或其他默认值
  fileTypeId: '',
  mimeType: '',
  name: ''
})
const loading = ref(true) // 列表的加载中

const publicList = ref([])
// 左侧图标数据
const treeIcon = {
  folder: '/static/iconVsg/DOCUMENT.png',
  file: '/static/iconVsg/FILE.png'
}
// 打印
const printList = ref([])
// 获取左侧列表数据
const getfileData = async () => {
  try {
    const typeLists = await datarApi.getList()
    if (typeLists.length > 0) {
      publicList.value = typeLists
      loading.value = false
    } else {
      loading.value = true
    }
  } catch (error) {
    loading.value = false
    console.log('失败123')
    // 在这里处理异常
  }
}

// 跳转至新增文件
const addfile = () => {
  router.push({ path: '/produce/addfile' })
}
// 列表数据
const tableData = ref([])
// 右侧列表图标数据
const iconList = ref([
  { type: 'doc', path: '/static/iconVsg/DOC.png' },
  { type: 'docx', path: '/static/iconVsg/DOCX.png' },
  { type: 'jpg', path: '/static/iconVsg/JPG.png' },
  { type: 'pdf', path: '/static/iconVsg/PDF.png' },
  { type: 'png', path: '/static/iconVsg/PNG.png' },
  { type: 'ppt', path: '/static/iconVsg/PPT.png' },
  { type: 'pptx', path: '/static/iconVsg/PPTX.png' },
  { type: 'zip', path: '/static/iconVsg/ZIP.png' }
])
const getTypeImg = (type) => {
  const icon = iconList.value.find((item) => item.type === type)
  return icon ? icon.path : null
}


let formdata
// 初始化获取数据列表
const getDataList = async () => {
  formdata = new FormData()
  formdata.append('earthquakeId', fileData.earthquakeId)
  formdata.append('fileTypeId', fileData.fileTypeId)
  formdata.append('mimeType', fileData.mimeType)
  formdata.append('name', fileData.name)
  formdata.append('pageNo', currentPage.value)
  formdata.append('pageSize', pageSize.value)
  formdata.append('divisionCode', produceName.value)
  try {
    const fileList = await datarApi.getData(formdata)
    tableData.value = fileList.list.map((item) => {
      let typeImg = getTypeImg(item.mimeType)
      // 将 createdAt 字段格式化
      return {
        ...item,
        createdAt: moment(item.createdAt).format('YYYY-MM-DD HH:mm:ss'),
        imgType: typeImg
      }
    })
    total.value = fileList.total
  } catch (error) {
    console.log('失败123')
    // 在这里处理异常
  }
}
// 初始化下拉数据
const getProduceList = async () => {
  try {
    const ProduceList = await datarApi.getProduce()
    produceName.value = ProduceList[0].divisionCode
    produceList.value = ProduceList
  } catch (error) {
    console.log('失败123')
    // 在这里处理异常
  }
}
const handleSelectChange = (value) => {
  isShow.value = value !== 'root';
  produceName.value = value
  getDataList()
}
// 选取的行数据
const handleSelectionChange = (selection) => {
  printList.value = selection
  idList = []
  filename = []
  selection.forEach((item) => {
    idList.push(item.id)
    filename.push(item.file)
    console.log(idList, 'bbb')
    console.log(filename, 'bbb')
  })
}

// 选择左侧列表
const handleNodeClick1 = (data) => {
  fileData.fileTypeId = data.id
  getDataList()
}

// 批量删除
const remove = async () => {
  // 显示确认对话框
  ElMessageBox.alert('是否确定删除', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    callback: async (action) => {
      console.log(action)
      if (action === 'confirm') {
        try {
          if (idList.length <= 0){
            ElMessage({
              type: 'info',
              message: '请选择要删除的文件！'
            })
            return
          }
          const response = await datarApi.deleteList(idList)
          ElMessage({
            type: 'success',
            message: '已删除！'
          })
          getDataList()
        } catch (error) {}
      } else {
        ElMessage({
          type: 'info',
          message: '已取消删除！'
        })
      }
    }
  })
}

// 批量下载
const downloadList = async () => {
  ElMessageBox.alert('是否确定下载', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    callback: async (action) => {
      if (action === 'confirm') {
        try {
          if (idList.length <= 0){
            ElMessage({
              type: 'info',
              message: '请选择要下载的文件！'
            })
            return
          }
          let format = new FormData()
          format.append('divisionCode', produceName.value)
          format.append('ids', idList)
          const response = await datarApi.download(format)
          if (filename.length == 1) {
            let markFile = filename[0].split('.').pop()
            console.log('--markFile：'+markFile)
            if (markFile == 'excel') {
              download.excel(response, filename[0])
            }
            if (markFile == 'word') {
              download.word(response, filename[0])
            }
            if (markFile == 'docx') {
              download.word(response, filename[0])
            }
            if (markFile == 'doc') {
              download.word(response, filename[0])
            }
            if (markFile == 'ppt') {
              download.pdf(response, filename[0])
            }
            if (markFile == 'pptx') {
              download.xml(response, filename[0])
            }
            if (markFile == 'zip') {
              download.zip(response, filename[0])
            }
            if (markFile == 'html') {
              download.html(response, filename[0])
            }
            if (markFile == 'pdf') {
              download.pdf(response, filename[0])
            }
            if (markFile == 'xml') {
              download.xml(response, filename[0])
            }
            if (markFile == 'markdown') {
              download.markdown(response, filename[0])
            }
            if (markFile == 'images') {
              download.images(response, filename[0])
            }
            if (markFile == 'png') {
              download.png(response, filename[0])
            }
            if (markFile == 'jpg') {
              download.jpg(response, filename[0])
            }
            if (markFile == 'jpeg') {
              download.jpeg(response, filename[0])
            }
            if (markFile == 'smwu') {
              console.log('smuw下载');
              download.smuw(response, filename[0])
            }
          } else {
            const currentTime = moment().format('YYYY-MM-DD HH:mm')
            download.zip(response, currentTime)
          }
          ElMessage({
            type: 'success',
            message: '已下载！'
          })
        } catch (error) {
          console.log('失败')
          // 在这里处理异常
        }
      } else {
        ElMessage({
          type: 'info',
          message: '已取消下载！'
        })
      }
    }
  })
}

// 打印
const handlePrint = async () => {
  let basurl = import.meta.env.VITE_BASE_URL
  if (printList.value.length == 1) {
    ElMessageBox.alert('是否确定打印', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      callback: async (action) => {
        if (action === 'confirm') {
          console.log(printList.value,'====');
          let urlList = `${basurl}/admin-api/quake/file/read?pdfPath=${encodeURIComponent(printList.value[0].filePath)}`
          window.open(urlList, '_blank');
        } else {
          ElMessage({
            type: 'info',
            message: '已取消打印！'
          })
        }
      }
    })
  } else {
    ElMessage({
      type: 'error',
      message: '请选择一项内容！'
    })
  }

}

// 关联地震
const jumpViewpage = (row) => {
  console.log(row, '----')
  router.push({
    path: '/earthquake/viewpage',
    query: { id: row.earthquakeId, earthquakeType: row.earthquakeType }
  })
}

// 预览
const Preview = (row) => {
  let previewUrl = row.filePath
  let basurl = import.meta.env.VITE_BASE_URL
  let urlList = `${basurl}/admin-api/quake/file/read?pdfPath=${previewUrl}`
  window.open(urlList)
}
//模糊查询
const selectByName = () => {
  getDataList()
}

//分页切换
const handleSizeChange = (e) => {
  pageSize.value = e
  getDataList()
}

const handleCurrentChange = (e) => {
  currentPage.value = e
  getDataList()
}
onMounted(async () => {
  getProduceList()
  getfileData()
  getDataList()
})
</script>

<style scoped>
.demo-tab {
  height: 100vh;
}

.zip {
  width: 20px;
  height: 20px;
}

/* ::v-deep .el-table td,
.el-table th.is-leaf {
    border-bottom: none;
} */

 :deep(.custom-header) {
   background-color: #f2f3f5 !important;
   /* 设置表头背景色 */
   color: #333 !important;
   /* 设置表头文字颜色 */
   font-weight: bold !important;
   /* 设置表头文字加粗 */
   height: 42px;
 }
</style>
